package com.hgyc.mom.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.common.entity.SysDict;
import com.hgyc.mom.common.entity.SysDictItem;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.common.service.SysDictService;
import com.hgyc.mom.common.util.FreeMarkerUtils;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.common.util.sql.SqlInjectionUtil;
import com.hgyc.mom.core.config.GenConfig;
import com.hgyc.mom.system.service.SysDictItemService;
import com.hgyc.mom.system.mapper.SysDictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统字典 服务实现类
 * </p>
 *
 * @author fwj
 * @since 2025-01-16
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Autowired
    private SysDictItemService sysDictItemService;

    @Override
    public void addDict(SysDict sysDict) {
        if (StringUtils.isEmpty(sysDict.getDictCode())) {
            throw new BizException("字典编码不能为空");
        }
        String dictCode = sysDict.getDictCode();
        SysDict existDict = this.getDictByCode(dictCode);
        if (existDict != null) {
            throw new BizException("该字典编码已存在");
        }
        this.saveOrUpdate(sysDict);
    }

    @Override
    public List<Map<String, String>> translateRelationTableByKeys(String table, String key, String column, List<String> values) {
        // 分割SQL获取表名和条件
        String filterSql = null;
        if(table.toLowerCase().indexOf("where")>0){
            String[] arr = table.split(" (?i)where ");
            table = arr[0];
            filterSql = arr[1];
        }

        // 3.SQL注入check
        SqlInjectionUtil.filterContent(table, key, column);
        SqlInjectionUtil.specialFilterContentForDictSql(filterSql);

        // 针对采用 ${}写法的表名和字段进行转义和check
        table = SqlInjectionUtil.getSqlInjectTableName(table);
        key = SqlInjectionUtil.getSqlInjectField(key);
        column = SqlInjectionUtil.getSqlInjectField(column);

        return baseMapper.translateRelationTableByKeys(table, key, column, filterSql, values);
    }

    /**
     * 根据字典编码获取字典
     * @param code 字典编码
     * @return 字典
     */
    private SysDict getDictByCode(String code) {
        LambdaQueryWrapper<SysDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDict::getDictCode, code);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public String generatorEnum(Long dictId) {
        // 参数校验
        if (dictId == null) {
            throw new BizException("字典ID不能为空");
        }

        // 获取字典数据
        SysDict sysDict = this.getById(dictId);
        if (sysDict == null) {
            throw new BizException("字典不存在，ID: " + dictId);
        }

        // 获取字典项
        List<SysDictItem> itemList = Collections.emptyList();
        try {
            itemList = sysDictItemService.getItemByCode(sysDict.getDictCode());
        } catch (Exception e) {
            throw new BizException("获取字典项失败: " + sysDict.getDictCode(), e);
        }

        // 准备模板数据
        Map<String, Object> data = new HashMap<>();
        data.put("className", StringUtils.convertToCamelCase(sysDict.getDictCode()));
        data.put("dictName", sysDict.getDictName());
        data.put("dictItems", itemList);
        data.put("author", GenConfig.getAuthor());
        data.put("datetime", Instant.now()); // 使用Java 8时间API

        // 使用模板引擎生成
        try {
            return FreeMarkerUtils.processTemplate("java/enum.java.ftl", data);
        } catch (Exception e) {
            throw new BizException("生成枚举类失败", e);
        }
    }
}
